package com.ufo.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class ReadFileFromResources {
    public static void main(String[] args){
        byURI();
        byNewFile();
    }

    private static void byURI() {
        URL resource = Thread.currentThread().getClass().getResource("/text.txt");
        System.out.println(resource);
        try {
            byte[] bytes = Files.readAllBytes(Paths.get(resource.toURI()));
            String result = new String(bytes, StandardCharsets.UTF_8);
            System.out.println("from uri: "+ result);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    private static void byNewFile() {
        File file = new File(URLDecoder.decode(Thread.currentThread().getClass().getResource("/text.txt").getPath()));
        FileReader fr = null;//FileReader是字符流
        try {
            System.out.print("by fileReader: ");
            fr=new FileReader(file);
            int data;
            while ((data = fr.read()) != -1) {
                System.out.print((char)data);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //this.getClass().getResource("/User4Test.json");

    }
}
